<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page language="java" import="java.lang.*" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "com.seniorproject.aims.*" %>
<%@ page import = "java.util.List" %>
<%@ page import="java.util.ArrayList"%>
<%@ page import = "java.util.Properties" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.io.File" %>
<%@ page import = "java.io.InputStream" %>
<%@page import="java.util.regex.Matcher"%>
<%@page import="java.util.regex.Pattern"%>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Edit Category Info</title>
	
	<link rel="stylesheet" type="text/css" href="css/stylev2.css" />
	<link rel="stylesheet" type="text/css" href="css/student-system.css" />
	<link rel="stylesheet" type="text/css" href="css/frame.css" />
	
	<style type="text/css">
		td {
			height: 50px;
		}
		
		input {
			font-size: 20px;
		}
		
		select {
			font-size: 20px;
		}
		a {
	      text-decoration:none;
	   	}
	</style>
</head>
<body>

<%
	//get session
	String strUser = String.valueOf(session.getAttribute("sUser"));
	HttpSession htp_session = request.getSession();
	
	// check session
	if (htp_session == null || htp_session.getAttribute("sUser") == null) {
	    // Forward the control to login.jsp if authentication fails or session expires
	    request.getRequestDispatcher("/login.jsp").forward(request,
	        response);
	}
	
	if("admin".equals(htp_session.getAttribute("sUser"))){%>
	<script>alert("This user dont have PERMISSION to access this zone.");</script>
	<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=admin_home.jsp"> 	
	<%}
	
	// get parameter from category_edit	
	int CurriculumIdOLD = Integer.parseInt(request.getParameter("CurriculumId"));
	int CategoryIdOLD = Integer.parseInt(request.getParameter("CategoryId"));
	String categoryNameOLD = new String(request.getParameter("categoryName").getBytes("ISO8859_1"),"UTF-8");
	int CreditOLD = Integer.parseInt(request.getParameter("Credit"));
			
	System.out.println("EDIT CurriculumId "+CurriculumIdOLD);////////try////////
	System.out.println("EDIT CategoryId "+CategoryIdOLD);////////try////////
	System.out.println("EDIT categoryName "+categoryNameOLD);////////try////////
	System.out.println("EDIT Credit "+CreditOLD);////////try////////

	//GET PERMISSION

		String name = String.valueOf(session.getAttribute("name"));
		String surname = String.valueOf(session.getAttribute("surname"));
		String role_name = String.valueOf(session.getAttribute("curriculum_role"));
		
		String department_id = String.valueOf(session.getAttribute("department_id"));
				
		System.out.println("name : " + name);///////////////////////////////
		System.out.println("department_id : " + department_id);/////////////////////////
		
		List<String> system_name = new ArrayList<String>();
		
		Permission permission = new Permission(strUser,name);
		permission.setCurriculumCreate(Boolean.valueOf(String.valueOf(session.getAttribute("curriculum_create"))));
		permission.setCurriculumDelete(Boolean.valueOf(String.valueOf(session.getAttribute("curriculum_delete"))));
		permission.setCurriculumRead(Boolean.valueOf(String.valueOf(session.getAttribute("curriculum_read"))));
		permission.setCurriculumUpdate(Boolean.valueOf(String.valueOf(session.getAttribute("curriculum_update"))));
		
		String permiss = "";
		if(permission.getCurriculumCreate()) {
			permiss = permiss + "Add";
		}
		if(permission.getCurriculumUpdate()) {
			if("".equals(permiss)) {
				permiss = permiss + "Edit";
			} else {
				permiss = permiss + " Edit";
			}
		}
		if(permission.getCurriculumRead()) {
			if("".equals(permiss)) {
				permiss = permiss + "Read";
			} else {
				permiss = permiss + " Read";
			}
		}
		if(permission.getCurriculumDelete()) {
			if("".equals(permiss)) {
				permiss = permiss + "Delete";
			} else {
				permiss = permiss + " Delete";
			}
		}
		
	///////////////////////////////////////////////////////////////////////////////////////////////////////////			
	//check permission
		if(!permission.getCurriculumUpdate()){%>
			<script>alert("This user dont have PERMISSION to access this zone.");</script>
			<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=curriculum_home.jsp"> 	
		<%}
	
	//set Database Connection
	String hostProps = "";
	String usernameProps  = "";
	String passwordProps  = "";
	String databaseProps = "";
	
	try {
		//get current path
		ServletContext servletContext = request.getSession().getServletContext();
		
		InputStream input = servletContext.getResourceAsStream("/properties/connectDB.properties");
		Properties props = new Properties();
		
		props.load(input);

		hostProps  = props.getProperty("host");
		usernameProps  = props.getProperty("username");
		passwordProps  = props.getProperty("password");
		databaseProps = props.getProperty("database");
	} catch (Exception e) { 
		out.println(e);  
	}
	
	// connect database
	Connection connect = null;		
	try {
		Class.forName("com.mysql.jdbc.Driver");
	
		connect =  DriverManager.getConnection("jdbc:mysql://" + hostProps  + "/" + databaseProps +
				"?user=" + usernameProps  + "&password=" + passwordProps + "&characterEncoding=tis620" );
	
		if(connect != null){
			System.out.println("Database Connect Sucesses.");
		} else {
			System.out.println("Database Connect Failed.");	
		}

	} catch (Exception e) {
		out.println(e.getMessage());
		e.printStackTrace();
	}
	
%>

	<div id="page-wrap">
			<div id="inside">
				<table border="0">
					<tr style="font-size:24px">
						<td width="600" height="100" style= "background-color: #273b80;border: 0px ;padding: 0px; 0px;" >
							<div id="header_banner-2"></div>
						</td>
						
						<td width="680" height="100" style= "background-color: #273b80;border: 0px;padding: 0px; 0px;" >
							<p align="right"><label><font size="4" color="#ffffff">username : <%=strUser%>&nbsp;&nbsp;</font></label></p>
							<a href="logout.jsp"><p align="right"><label style="cursor: pointer;"><font size="3" color="#ffffff">log out &nbsp;</font></label></p></a>
						</td>
					</tr>
				</table>
        		
        		<div id="main-content-ac">
        					<div class="imageFrame">แก้ไขข้อมูลหมวดวิชา</div>
							<br/><br/><br/><br/><br/>
        						<center>        						      						
	        						<table border="0" width="800"> 									
										<tr style="font-size:20px">
											<form id="form" name="form" method="post" action="">  		
													
													<input type="hidden" id="CurriculumId" name="CurriculumId" value="<%=CurriculumIdOLD%>" /> 
													<input type="hidden" id="CategoryId" name="CategoryId" value="<%=CategoryIdOLD%>" /> 
													
													<input type="hidden" id="categoryName" name="categoryName" value="<%=categoryNameOLD%>" /> 
												<tr>	
													<td>
														<label for="labelcategoryName"> <font size="5"><strong>ชื่อหมวดวิชา</strong></font></label>
														<label><font size="5" color="#FF0000">*</font></label>
													</td>
													<td>
														<input type="text" name="categoryNameInfo" id="categoryNameInfo" required value="<%=categoryNameOLD%>" />
														<input type="hidden" id="categoryName" name="categoryName" value="<%=categoryNameOLD%>" /> 
													</td>
													
												</tr>	
												<tr>	
													<td>
														<label for="labelCredit"> <font size="5"><strong>หน่วยกิต</strong></font> </label>
														<label><font size="5" color="#FF0000">*</font></label>
													</td>
													<td>
														<input type="text" name="CreditInfo" id="CreditInfo" required value="<%=CreditOLD%>" />  
														<input type="hidden" name="Credit" id="Credit" value="<%=CreditOLD%>" />
													</td>
													
												</tr>
										
											
												<td><input type="submit" value="save" name="save" class="buttonStyle"/></td>
											
											</form>								
																							
												<td><a href="curriculum_category_edit.jsp"><button class="buttonStyle" >cancel</button></a></td>
							
										</tr>
								</table>
							</center>
							
						<br><br><br><br><br><br><br><br>	
						</div>
					<div style="clear: both;"></div>
						<div id="footer"></div>
			</div>		
						<div style="clear: both;"></div>		
	</div>
	
<%
		String checkButton = request.getParameter("save");
		System.out.println("checkButton : "+checkButton);////////////////////try///////////////////
		// check save button is pressed
		if("save".equals(checkButton)) {

				//request.setCharacterEncoding("UTF-8");
				
				// get value from tag
				String categoryNameNEW = new String(request.getParameter("categoryNameInfo").getBytes("ISO8859_1"),"UTF-8");
				String CreditNEW = request.getParameter("CreditInfo");
				
 //////////////////////////////CHECK IF INPUT WERE SPECIAL CHARACTERS> //////////////////////
					Pattern regex = Pattern.compile("[$&+,:;=?@#^*)(|!%]");
					Matcher matchertempCredit_category = regex.matcher(categoryNameNEW);
					Matcher matchertempcategoryName = regex.matcher(CreditNEW);
								
		if (matchertempCredit_category.find() || matchertempcategoryName.find()){
		%>
			<script language="javascript"> alert("ข้อมูลไม่ถูกต้อง โปรดใช้ตัวเลขหรือตัวอักษรเท่านั้น");	</script>
		<%}else{				
				boolean checker = CreditNEW.matches("[-+]?\\d+(\\.\\d+)?");
				System.out.println("checker: "+checker);
				
				System.out.println("categoryName OLD : "+categoryNameOLD);////////////////////try///////////////////
				System.out.println("categoryName NEW : "+categoryNameNEW);////////////////////try///////////////////
				System.out.println("Credit OLD : "+CreditOLD);////////////////////try///////////////////
				System.out.println("Credit NEW : "+CreditNEW);////////////////////try///////////////////
				
				if(checker){
					try {							
						connect.createStatement().executeUpdate("UPDATE `subject_category` SET `category_name`='"+ categoryNameNEW + "', "
								+ " `credit`=" + CreditNEW							
								+ " WHERE category_id="+CategoryIdOLD);
						
						String sql_subject_category = "UPDATE `subject_category` SET `category_name`='"+ categoryNameNEW + "', "
								+ " `credit`=" + CreditNEW							
								+ " WHERE category_id="+CategoryIdOLD;
						
						/* Log file */
						String log_user = strUser+" edit subject_category";
						Log.writeUserFile(log_user);
						Log.writeUserFile(sql_subject_category);
						
						
	%>
						<script language="javascript"> alert("แก้ไขข้อมูลสำเร็จ");	</script>
						<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=curriculum_category_edit.jsp">
						
	<%
					} catch (SQLException e) {
						e.printStackTrace();
					}	
				}else{//checker%>
					<script language="javascript"> alert("กรุณาใส่หน่วยกิตด้วยตัวเลขค่ะ");</script>		
				<%}
		}//else special
			}
		
		connect.close();
%>				
</body>
</html>